//
//  ForgetPwdVC.m
//  GasCome
//
//  Created by zfc on 2020/4/25.
//  Copyright © 2020 zfc. All rights reserved.
//

#import "ForgetPwdVC.h"

@interface ForgetPwdVC () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *phoneTf;
@property (nonatomic, strong)  UITextField *codeTf;
@property (nonatomic, strong) UITextField *firstPwdTf;
@property (nonatomic, strong) UITextField *secondPwdTf;

@end

@implementation ForgetPwdVC

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.presentingViewController == nil) {
        self.fd_prefersNavigationBarHidden = NO;
        self.fd_interactivePopDisabled = NO;
        self.navigationItem.title = @"修改密码";
    } else {
        self.fd_prefersNavigationBarHidden = YES;
        self.fd_interactivePopDisabled = YES;
    }


    [self setUI];
    
    [self.phoneTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.codeTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.firstPwdTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.secondPwdTf addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
}

- (void) setUI {
    self.view.backgroundColor = WhiteColor;
    UIImageView *logoImgV = [[UIImageView alloc] init];
    logoImgV.image = [UIImage imageNamed:@"register_ic_logo"];
    [self.view addSubview:logoImgV];
    CGFloat f = self.presentingViewController == nil ? 30 : 30+kTopHeight;
    [logoImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(f);
    }];

    UIButton *toLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [toLoginBtn setTitle:@"去登录" forState:UIControlStateNormal];
    toLoginBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [toLoginBtn setTitleColor:BlackColor forState:UIControlStateNormal];
    [self.view addSubview:toLoginBtn];
    [toLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view).offset(-15);
        make.top.equalTo(self.view).offset(10+kToolHeight);
    }];
    toLoginBtn.block = ^(UIButton *sender) {
        [self.navigationController popViewControllerAnimated:YES];
    };
    toLoginBtn.hidden = self.presentingViewController == nil;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"common_ic_back"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"common_ic_back"] forState:UIControlStateNormal];

    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(15);
        make.top.equalTo(self.view).offset(10+kToolHeight);
    }];
    backBtn.block = ^(UIButton *sender) {
        [self.navigationController popViewControllerAnimated:YES];
    };
    backBtn.hidden = self.presentingViewController == nil;

    //手机号视图
    UIView *phoneView = [[UIView alloc] init];
    [self.view addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(logoImgV.mas_bottom).offset(6);
        make.height.mas_equalTo(60);
    }];

    UIImageView *phoneImgV = [[UIImageView alloc] init];
    phoneImgV.image = [UIImage imageNamed:@"register_ic_phone"];
    [phoneView addSubview:phoneImgV];
    [phoneImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(phoneView);
        make.leading.equalTo(phoneView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *phoneTf = [[UITextField alloc] init];
    NSAttributedString *phoneAttr = [[NSAttributedString alloc] initWithString:@"请输入您的手机号" attributes:
    @{NSForegroundColorAttributeName:Color999,
        NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];

    phoneTf.attributedPlaceholder = phoneAttr;
    phoneTf.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTf];
    self.phoneTf = phoneTf;
    [phoneTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(phoneImgV.mas_trailing).offset(20);
        make.centerY.equalTo(phoneView);
        make.trailing.equalTo(phoneView).offset(-10);
    }];

    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = ColorE6;
    [phoneView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(phoneView);
        make.height.mas_equalTo(0.5);
    }];

    //手机号视图
    UIView *codeView = [[UIView alloc] init];
    [self.view addSubview:codeView];
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(phoneView.mas_bottom).offset(6);
        make.height.mas_equalTo(60);
    }];

    UIImageView *codeImgV = [[UIImageView alloc] init];
    codeImgV.image = [UIImage imageNamed:@"register_ic_code"];
    [codeView addSubview:codeImgV];
    [codeImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(codeView);
        make.leading.equalTo(codeView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *codeTf = [[UITextField alloc] init];
    NSAttributedString *codeAttr = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:
    @{NSForegroundColorAttributeName:Color999,
        NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];

    codeTf.attributedPlaceholder = codeAttr;
    codeTf.keyboardType = UIKeyboardTypeNumberPad;
    [codeView addSubview:codeTf];
    self.codeTf = codeTf;
    [codeTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(codeImgV.mas_trailing).offset(20);
        make.centerY.equalTo(codeView);
        make.trailing.equalTo(codeView).offset(-90);
    }];

    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [codeBtn setTitle:@"  发送验证码  " forState:UIControlStateNormal];
    [codeBtn setTitleColor:Color333 forState:UIControlStateNormal];
    codeBtn.titleLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
    codeBtn.cornerRadius = 1.5;
    codeBtn.borderColor = Color999;
    codeBtn.borderWidth = 0.5;
    [codeView addSubview:codeBtn];
    [codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(28);
//        make.width.mas_equalTo(80);
        make.centerY.equalTo(codeView);
        make.trailing.equalTo(codeView);
    }];
    codeBtn.block = ^(UIButton *sender) {
        //点击发送验证码
        [self actionGetCode:sender];

    };

    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = ColorE6;
    [codeView addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(codeView);
        make.height.mas_equalTo(0.5);
    }];


    //密码视图
    UIView *firstPwdView = [[UIView alloc] init];
    [self.view addSubview:firstPwdView];
    [firstPwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(codeView.mas_bottom);
        make.height.mas_equalTo(60);
    }];

    UIImageView *firstPwdImgV = [[UIImageView alloc] init];
    firstPwdImgV.image = [UIImage imageNamed:@"register_ic_password"];
    [firstPwdView addSubview:firstPwdImgV];
    [firstPwdImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(firstPwdView);
        make.leading.equalTo(firstPwdView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *firstPwdTf = [[UITextField alloc] init];
    NSAttributedString *firstPwdAttr = [[NSAttributedString alloc] initWithString:@"请输入您的密码" attributes:
    @{NSForegroundColorAttributeName:Color999,
        NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];

    firstPwdTf.attributedPlaceholder = firstPwdAttr;
    [firstPwdView addSubview:firstPwdTf];
    self.firstPwdTf = firstPwdTf;
    [firstPwdTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(firstPwdImgV.mas_trailing).offset(20);
        make.centerY.equalTo(firstPwdView);
        make.trailing.equalTo(firstPwdView).offset(-10);
    }];

    UIView *lineView2 = [[UIView alloc] init];
    lineView2.backgroundColor = ColorE6;
    [firstPwdView addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(firstPwdView);
        make.height.mas_equalTo(0.5);
    }];


    //确认密码视图
    UIView *secondPwdView = [[UIView alloc] init];
    [self.view addSubview:secondPwdView];
    [secondPwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.top.equalTo(firstPwdView.mas_bottom);
        make.height.mas_equalTo(60);
    }];

    UIImageView *secondPwdImgV = [[UIImageView alloc] init];
    secondPwdImgV.image = [UIImage imageNamed:@"register_ic_password"];
    [secondPwdView addSubview:secondPwdImgV];
    [secondPwdImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(secondPwdView);
        make.leading.equalTo(secondPwdView);
        make.height.width.mas_equalTo(24);
    }];

    UITextField *secondPwdTf = [[UITextField alloc] init];
    NSAttributedString *secondPwdAttr = [[NSAttributedString alloc] initWithString:@"请输入您的密码" attributes:
    @{NSForegroundColorAttributeName:Color999,
        NSFontAttributeName:[UIFont systemFontOfSize:14]
    }];

    secondPwdTf.attributedPlaceholder = secondPwdAttr;
    [secondPwdView addSubview:secondPwdTf];
    self.secondPwdTf = secondPwdTf;
    [secondPwdTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(secondPwdImgV.mas_trailing).offset(20);
        make.centerY.equalTo(secondPwdView);
        make.trailing.equalTo(secondPwdView).offset(-10);
    }];

    UIView *lineView3 = [[UIView alloc] init];
    lineView3.backgroundColor = ColorE6;
    [secondPwdView addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(secondPwdView);
        make.height.mas_equalTo(0.5);
    }];


    UIButton *changePwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [changePwdBtn setTitle:@"确定" forState:UIControlStateNormal];
    [changePwdBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    changePwdBtn.cornerRadius = 8;
    changePwdBtn.backgroundColor = [UIColor bm_colorGradientChangeWithSize:CGSizeMake(kScreenW-140, 50) direction:IHGradientChangeDirectionLevel startColor:[UIColor colorWithHexString:@"F74040"] endColor:[UIColor colorWithHexString:@"FAC966"]];
    [self.view addSubview:changePwdBtn];
    [changePwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-65-kBottomWhiteHeight);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.leading.equalTo(self.view).offset(70);
    }];

    changePwdBtn.block = ^(UIButton *sender) {
        //注册
        [self changePwd];
    };

    self.firstPwdTf.delegate = self;
    self.secondPwdTf.delegate = self;

}

- (void) changePwd {
    BOOL isValid = [Untils cheackPhoneNumValid:self.phoneTf.text];
    if(!isValid){
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        return;
    }

    if (self.codeTf.text.length != 4) {
        [SVProgressHUD showInfoWithStatus:@"请输入4位手机验证码"];
        return;
    }

//    BOOL firstPwdValid = [Untils cheackPasswordValid:self.firstPwdTf.text];
    if (self.firstPwdTf.text.length < 6 || self.firstPwdTf.text.length > 15) {
        [SVProgressHUD showInfoWithStatus:@"密码格式错误"];
        return;
    }

//    BOOL secondPwdValid = [Untils cheackPasswordValid:self.secondPwdTf.text];
    if (self.secondPwdTf.text.length < 6 || self.secondPwdTf.text.length > 15) {
        [SVProgressHUD showInfoWithStatus:@"确认密码格式错误"];
        return;
    }

    if (![self.firstPwdTf.text isEqualToString:self.secondPwdTf.text]) {
        [SVProgressHUD showInfoWithStatus:@"请确认两次密码一致"];
        return;
    }

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = self.phoneTf.text;
    params[@"code"] = self.codeTf.text;
    params[@"password"] = self.firstPwdTf.text;
    params[@"password_repetition"] = self.secondPwdTf.text;
    params[@"group"] = @"tinyShopApp";

    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:@"/api/tiny-shop/v1/site/up-pwd" params:params successBlock:^(NSDictionary * _Nonnull response) {
        

        //使用归档保存数据
        LoginModel *model = [LoginModel mj_objectWithKeyValues:response[@"data"]];
        [[UserAccountManager shared] saveUser:model];
//        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsSalesMan];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kLoginWayChange object:nil];
        //注册成功
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        [JPushFunc pushJPushRegisterID];

    } failureBlock:^(NSError * _Nonnull error) {

    }];
}

- (void)actionGetCode:(id)sender {
    BOOL isValid = [Untils cheackPhoneNumValid:self.phoneTf.text];
    if(!isValid){
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        return;
    }

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = self.phoneTf.text;
    params[@"usage"] = @"up-pwd";

    [[NetWorksTools shared] requestWithNotTokenMethod:POST url:@"/api/tiny-shop/v1/site/sms-code" params:params successBlock:^(NSDictionary * _Nonnull response) {
        NSLog(@"重置密码验证码: %@", response[@"data"]);
        //倒计时状态下的颜色
        [self setTheCountdownButton:sender startWithTime:59 title:@"重新获取"countDownTitle:@"s"mainColor:WhiteColor countColor:WhiteColor countTitleColor:Color999];
    } failureBlock:^(NSError * _Nonnull error) {

    }];
}


#pragma mark - button倒计时
- (void)setTheCountdownButton:(UIButton *)button startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(UIColor *)mColor countColor:(UIColor *)color countTitleColor:(UIColor *)titleColor{
    //倒计时时间
    NSInteger endTime = [[NSDate date] timeIntervalSince1970] + timeLine;

    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    //每秒执行一次
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0), 1.0 * NSEC_PER_SEC,0);
    dispatch_source_set_event_handler(_timer, ^{
        NSInteger currentTIme = [[NSDate date] timeIntervalSince1970];

        //倒计时结束，关闭
        if (endTime <= currentTIme) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                button.backgroundColor = mColor;
                [button setTitle:[NSString stringWithFormat:@"  %@  ", title] forState:UIControlStateNormal];
                button.userInteractionEnabled =YES;
            });
        } else {
            NSString *timeStr = [NSString stringWithFormat:@"  %@(%ld%@)  ", title,endTime-currentTIme, subTitle];
            dispatch_async(dispatch_get_main_queue(), ^{
                button.backgroundColor = color;
                [button setTitleColor:titleColor forState:UIControlStateNormal];
                [button setTitle:timeStr forState:UIControlStateNormal];
                button.userInteractionEnabled = NO;
            });
        }
    });
    dispatch_resume(_timer);
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@" "] || [Untils isChinese:string]) {
        return NO;
    } else {
        return YES;
    }
}

-(void)changedTextField:(UITextField *)textField {

    if (textField == self.phoneTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    
    if (textField == self.codeTf) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }
    
    if (textField == self.firstPwdTf) {
        if (textField.text.length > 15) {
            textField.text = [textField.text substringToIndex:15];
        }
    }
    
    if (textField == self.secondPwdTf) {
        if (textField.text.length > 15) {
            textField.text = [textField.text substringToIndex:15];
        }
    }

}

@end
